package com.hiray.ui.main

import android.annotation.SuppressLint
import android.app.Activity.RESULT_OK
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.provider.MediaStore
import android.support.design.widget.BottomSheetDialog
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.hiray.R
import com.hiray.di.component.MainComponent
import com.hiray.mvp.p.UserPresenter
import com.hiray.mvp.v.AvatarView
import com.hiray.ui.my.AccountSettingActivity
import com.hiray.ui.BaseFragment
import com.hiray.ui.FragmentChangeListener
import com.hiray.ui.WebViewActivity
import com.hiray.ui.my.CropImageActivity
import com.hiray.ui.my.MyDetailActivity
import com.hiray.ui.my.withdraw.WithDrawRecordActivity
import com.hiray.util.Store
import com.hiray.util.Toasty
import com.hiray.widget.GridItemDecoration
import kotlinx.android.synthetic.main.fragment_my.*
import java.io.File
import javax.inject.Inject

@SuppressLint("LogNotTimber")
class MyFragment : BaseFragment(), View.OnClickListener, AvatarView {
    private val TAG = "MyFragment"
    private lateinit var statusBarHandler: FragmentChangeListener
    private lateinit var gridItemDecoration: GridItemDecoration


    @Inject
    lateinit var userPresenter: UserPresenter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        getComponent(MainComponent::class.java)
                .inject(this)
        userPresenter.avatarView = this
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_my, container, false)
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            statusBarHandler.setStatusBarColor(R.color.colorPlanetBg)
        }
    }

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        statusBarHandler = context as FragmentChangeListener
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        username.text = "阿扎芭芭拉"
        userId.text = "ID:10001"
        userRank.setImageResource(R.drawable.ic_level_elder)
        userRankName.text = "星球战士"

        setting.setOnClickListener(this)
        user_avatar.setOnClickListener(this)
        my_detail.setOnClickListener(this)
        my_rank.setOnClickListener(this)
        my_friend.setOnClickListener(this)
        my_withdrawRecord.setOnClickListener(this)
        my_tipsbook.setOnClickListener(this)
        my_activity.setOnClickListener(this)

    }


    override fun onClick(v: View) {
        when (v.id) {
            R.id.setting -> startActivity(Intent(activity!!, AccountSettingActivity::class.java))
            R.id.user_avatar -> popAvatarChoiceSheet()
            R.id.my_detail -> startActivity(Intent(activity!!, MyDetailActivity::class.java))
            R.id.my_rank -> WebViewActivity.load(activity!!, Store.URL_RANK_AGREEMENT)
            R.id.my_friend -> WebViewActivity.load(activity!!, Store.URL_RANK_AGREEMENT)
            R.id.my_withdrawRecord -> startActivity(Intent(activity!!, WithDrawRecordActivity::class.java))
            R.id.my_tipsbook -> WebViewActivity.load(activity!!, Store.URL_TIPS)
            R.id.my_activity -> WebViewActivity.load(activity!!, Store.URL_ACTIVITY)
        }
    }

    private val REQUEST_ALBUM = 0x00
    private lateinit var dialog: BottomSheetDialog

    /**
     * 更换头像弹窗
     */
    private fun popAvatarChoiceSheet() {
        dialog = BottomSheetDialog(activity!!)
        val view = layoutInflater.inflate(R.layout.avatar_change_dialog, null)
        dialog.setContentView(view)
        view.findViewById<View>(R.id.uploadAvatar).setOnClickListener {
            val albumIntent = Intent(Intent.ACTION_PICK)
            albumIntent.data = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            startActivityForResult(albumIntent, REQUEST_ALBUM)
        }
        view.findViewById<View>(R.id.cancel).setOnClickListener { dialog.dismiss() }
        view.findViewById<View>(R.id.changeDefaultAvatar).setOnClickListener {}
        (view.parent as ViewGroup).setBackgroundResource(android.R.color.transparent)
        dialog.show()

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK)
            if (requestCode == REQUEST_ALBUM)//获取到图片，然后请求裁切
                CropImageActivity.start(this, data!!.data)
            else if (requestCode == CropImageActivity.REQUEST_CROP) {
                //裁切之后的图片uri
                Log.i(TAG, "onActivityResult: ${data!!.data}")
                user_avatar.setImageURI(data.data)
                userPresenter.uploadAvatar(File(data.data.path))
                dialog.dismiss()
            }
    }

    override fun onAvatarChange(avatarUrl: String) {

    }


    @SuppressWarnings("unused")
    private inner class MyDetailInnerAdapter : RecyclerView.Adapter<ItemViewHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ItemViewHolder(layoutInflater.inflate(R.layout.item_my, parent, false))


        override fun getItemCount() = 6
        override fun onBindViewHolder(holder: ItemViewHolder, position: Int) = holder.bind()

    }

    inner class ItemViewHolder : RecyclerView.ViewHolder {

        fun bind() {
//            Log.i(TAG, ": =====================width: ${rv.measuredWidth}  height: ${rv.measuredHeight}")
            itemView.setOnClickListener({
                Toasty.message("you click item:${adapterPosition}")
            })
        }

        constructor(itemView: View?) : super(itemView) {
            val lp = itemView?.layoutParams as GridLayoutManager.LayoutParams
            lp.width = (view!!.measuredWidth - gridItemDecoration.verticalSpan * 2) / 3
            lp.height = (view!!.measuredHeight / 2 - gridItemDecoration.horizontalSpan) / 2
//            Log.i(TAG, ": width: ${header_my_layout.measuredWidth}  height: ${header_my_layout.measuredHeight}")
            itemView.layoutParams = lp
        }
    }
}


